package cn.fetosoft.woodpecker.core.data.service.impl;

import cn.fetosoft.woodpecker.core.data.base.AbstractMongoService;
import cn.fetosoft.woodpecker.core.data.entity.Scheduled;
import cn.fetosoft.woodpecker.core.data.entity.User;
import cn.fetosoft.woodpecker.core.data.entity.element.TestPlanElement;
import cn.fetosoft.woodpecker.core.data.form.ScheduledForm;
import cn.fetosoft.woodpecker.core.data.service.ElementService;
import cn.fetosoft.woodpecker.core.data.service.ScheduledService;
import cn.fetosoft.woodpecker.core.data.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时服务
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/7/27 16:28
 */
@Slf4j
@Service
public class ScheduledServiceImpl extends AbstractMongoService<Scheduled, ScheduledForm> implements ScheduledService {

	@Autowired
	private ElementService elementService;
	@Autowired
	private UserService userService;

	@Override
	public List<Scheduled> selectListByForm(ScheduledForm form) {
		try {
			List<Scheduled> scheduleds = this.selectListByForm(form, Scheduled.class);
			if(!CollectionUtils.isEmpty(scheduleds)){
				Map<String, TestPlanElement> elementMap = new HashMap<>();
				Map<String, User> userMap = new HashMap<>();
				for(Scheduled s : scheduleds){
					TestPlanElement element = elementMap.get(s.getPlanId());
					if(element==null){
						element = (TestPlanElement) elementService.findById(s.getPlanId(), TestPlanElement.class);
						if(element!=null){
							elementMap.put(s.getPlanId(), element);
						}
					}
					User user = userMap.get(s.getUserId());
					if(user==null){
						user = userService.findByUserId(s.getUserId());
						if(user!=null){
							userMap.put(s.getUserId(), user);
						}
					}

					if(element!=null) {
						s.setPlanName(element.getName());
					}else{
						s.setPlanName("测试计划已删除");
					}
					if(user!=null){
						s.setUsername(user.getName());
					}else{
						s.setUsername("用户已删除");
					}
				}
				userMap.clear();
				elementMap.clear();
				return scheduleds;
			}
		} catch (Exception e) {
			log.error("selectListByForm", e);
		}
		return new ArrayList<>();
	}
}
